<?php

namespace app\frontend\controller;

use app\common\gt3\GeetestLib;
use app\common\model\Avatar;
use app\common\model\Users;
use think\Controller;
use think\Request;

class Index extends Controller
{
    public function index()
    {

        return $this->fetch('index/index');
    }

    //注册
    public function register(Request $request)
    {
        //前端ajax验证唯一性
        if($request->isAjax()){
            $data=$request->post();
            $field=key($data);
            switch($field){
                case 'name':
                    $bool=Users::where('nickname',current($data))->find();
                    if(!$bool){
                        return true;
                    }else{
                        return "此昵称已存在";
                    }
                    break;
                case 'email':
                    $bool=Users::where('email',current($data))->find();
                    if(!$bool){
                        return true;
                    }else{
                        return '此邮箱已存在';
                    }
            }
        }

        //Get显示注册页面
        if($request->isGet()) {
            return $this->fetch();
        }

        //获取请求信息
        $name=$request->post('name');
        $email=$request->post('email');
        $pwd=$request->post('password');
        $pwd_confirm=$request->post('password_confirmation');

        if($pwd !== $pwd_confirm){
            return renderJs('两次密码不相同,请重新填写注册信息');
        }

        //$password=password_hash($pwd,PASSWORD_BCRYPT);

        //验证
        $res=$this->validate($request->post(),[
            'name' =>'require|length:3,20|unique:users,nickname|token',
            'email' => 'require|email|unique:users',
            'password' => 'require|length:3,20',
            'password_confirmation' => 'require|confirm:password'
        ]);

        if($res !==true){
            return renderJs($res);
        }

        //发送email验证信息
        $regtime=time();
        $token=md5($name.$regtime);
        $url="http://".$_SERVER['HTTP_HOST']."/frontend/index/act?act=active&token={$token}";
        $urlencode=urlencode($url);
        $mailer_str=<<<EOF
亲爱的{$name}您好!感谢您注册我们网站<br/>
请点击此链接激活账号即可登录！<br/>
<a href="{$url}">{$urlencode}</a><br/>
如果点击链接无反应，可以将其复制到浏览器中执行,链接有效期为24小时,过时失效.
EOF;

        //发送邮件
        $mailer_bool=send_email($email,'TpBlog网站激活邮件',$mailer_str);
        if($mailer_bool){
            //写入数据库
            $user=new Users;
            $user->nickname=$name;
            $user->email=$email;
            $user->password=password_hash($pwd,PASSWORD_BCRYPT);
            $user->email_token=$token;
            $user->create_time=$regtime;
            $user->update_time=$regtime;
            $user->save();

            return renderJs('注册成功,正在跳转至登录页面','/login');
        }else{
            $this->error(\Swift_SwiftException::getMessage());
        }
    }

    //激活邮箱
    public function act(Request $request){
        $req=$request->get();
        $user_info=Users::where('email_token',$req['token'])->find();
        if(!$user_info){
            return '<script>alert("无效的操作");window.location.href="/register"</script>';
        }

        //如果状态为1
        if($user_info->status==1){
            return renderJs('您已经注册,正在跳转至登录页','/login');
        }

        $update_time=$user_info->update_time;
        if($update_time+config('swift.Email_Expire_Time') < time()){
            //TODO 并没有过期后的逻辑
            return $this->error('已过期');
        }else{
            //status 0===>1
            $user_info->status=1;
            $user_info->save();

            return renderJs('激活成功正在跳转至登录页面','/login');
        }
    }

    //登录
    public function login(Request $request){
        //显示登录页面
        if($request->isGet()) {
            if(session('name') && session('uid')){
                //没有数据库验证数据
                return $this->redirect('/');
            }

//            var_dump(date('Y-m-d H:i:s',1523861705));
            return $this->fetch('login');
        }

        //二次验证开始
        if(session('gtserver')!==1){
            return renderJs('验证服务器连接失败');
        }
        //二次验证
        $GtSdk = new GeetestLib(config('gt3.captcha_id'),config('gt3.private_key'));
        $result=$GtSdk->success_validate($request->post('geetest_challenge'),$request->post('geetest_validate'),$request->post('geetest_seccode'),config('gt3.req_params'));

        if(!$result){
            return renderJs('二次验证失败,验证码已过期');
        }

        //获取数据
        #var_dump($request->post());
        $email=$request->post('email');
        $pwd=$request->post('password');
        $is_remember=$request->post('is_remember');
        $__token__=$request->post('__token__');

        #var_dump($_token);exit;
        $data=compact('__token__','email','pwd','is_remember');

        //简单表单验证
        $validate_res=$this->validate($data,[
            'email'=>'require|email|token',
            'pwd'=>'require'
        ],[
            'email.require'=>'请填写注册邮箱地址',
            'pwd.require'=>'请填写登录密码'
        ]);

        if($validate_res !==true){
            return renderJs($validate_res);
        }

        //登录名与密码正确性验证
        $user_info=Users::where('email',$email)->find();
        if(password_verify($pwd,$user_info->password)){
//            return renderJs('Ok');
            //如果status状态为0
            if($user_info->status == 0){
                //激活时间已经过期
                $expire_time=$user_info->update_time+config('swift.Email_Expire_Time');
                if($expire_time < time()){
                    //发送email验证信息
                    $regtime=time();
                    $token=md5($user_info->nickname.$regtime);
                    $url="http://".$_SERVER['HTTP_HOST']."/frontend/index/act?act=active&token={$token}";
                    $urlencode=urlencode($url);
                    $mailer_str=<<<EOF
亲爱的{$user_info->nickname}您好!感谢您注册我们网站<br/>
请点击此链接激活账号即可登录！<br/>
<a href="{$url}">{$urlencode}</a><br/>
如果点击链接无反应，可以将其复制到浏览器中执行,链接有效期为24小时,过时失效.
EOF;

                    //发送邮件
                    $mailer_bool=send_email($email,'TpBlog网站激活邮件',$mailer_str);
                    if($mailer_bool){
                        //写入数据库
                        $user_info->email_token=$token;
                        $user_info->update_time=$regtime;
                        $user_info->save();

                        #return $this->redirect('/register');
                        return renderJs('激活时间已过,已重新发送邮件,请查收激活');
                    }else{
                        $this->error(\Swift_SwiftException::getMessage());
                    }
                }

                //激活时间未过期,提示激活邮箱,跳转至注册页
                $expires=($user_info->update_time)+config('swift.Email_Expire_Time');
                $time_remain=($expires-time())/60;
                return renderJs("请激活邮箱后登录,剩余时间{$time_remain}分钟");
            }
            //状态为1,可登陆状态
            if($user_info->status==1){
                session('uid',$user_info->uid);
                session('name',$user_info->nickname);

                //查询用户是否有头像
                $avatar_info=Avatar::where('user_id',$user_info->uid)->find();
                if($avatar_info){
                    session('avatar_url',$avatar_info->img_url);
                }
                //保持登录状态
                if($is_remember){
                    //TODO 保持登录状态方法
                    cookie(session_name(),session_id(),config('session.expire_time'));
                }

                return $this->redirect('/');
            }

            //status既不 =1 也不 =0
            return renderJs('用户状态不合法');
        }else{
            return renderJs('邮箱地址或密码错误');
        }
    }

    //初始化,首次验证
    public function startCaptchaServlet(){
        $GtSdk = new GeetestLib(config('gt3.captcha_id'),config('gt3.private_key'));;

        $data=config('gt3.req_params');
        $status = $GtSdk->pre_process($data, 1);
        session('gtserver',$status);
        session('user_id',$data['user_id']);
        echo $GtSdk->get_response_str();
    }

    //注销
    public function logout(){
        $uid=session('uid');
        $name=session('name');
        $user_info=Users::where('uid',$uid)->where('nickname',$name)->find();
        if($user_info){
            session('name',null);
            session('uid',null);
            session('avatar_url',null);
            return $this->redirect('/login');
        }

        return renderJs('非法数据用户操作','/login');
    }

}
